import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import "font-awesome/css/font-awesome.min.css";
import axios from "axios";
import qs from "qs";
import {
  getCurDate,
  setSessionStorage,
  getSessionStorage,
  removeSessionStorage,
  setLocalStorage,
  getLocalStorage,
  removeLocalStorage,
} from "./common.js";

//设置axios的基础url部分
axios.defaults.baseURL = "/api/";
//将axios挂载到vue实例上，使用时就可以 this.$axios 这样使用了

axios.interceptors.request.use(
  (config) => {
    if (!config.url.startsWith("https://qianfan.baidubce.com")) {
      const token = sessionStorage.getItem("token");
      if (token) {
        config.headers.Authorization = "Bearer " + token;
      }
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

router.beforeEach((to, from, next) => {
  const userId = sessionStorage.getItem("userId");
  const userName = sessionStorage.getItem("userName");
  const token = sessionStorage.getItem("token");
  // 除了登录、注册、首页、商家列表、商家信息、我的页面之外，都需要判断是否登录
  const whiteList = [
    "/",
    "/userIndex",
    "/businessList",
    "/my",
    "/login",
    "/register",
    "/aiAssistant",
  ];
  if (!whiteList.includes(to.path) && !(userName || userId || token)) {
    // 用 next 重定向，避免在守卫里再调用 router.push
    if (from.path !== "/login") {
      window.alert("请先登录后再访问该页面！");
    }
    return next("/login");
  }
  next();
});

const app = createApp(App);

app.config.compatConfig = { MODE: 2 };

app.config.globalProperties.$axios = axios;
app.config.globalProperties.$qs = qs;
app.config.globalProperties.$getCurDate = getCurDate;
app.config.globalProperties.$setSessionStorage = setSessionStorage;
app.config.globalProperties.$getSessionStorage = getSessionStorage;
app.config.globalProperties.$removeSessionStorage = removeSessionStorage;
app.config.globalProperties.$setLocalStorage = setLocalStorage;
app.config.globalProperties.$getLocalStorage = getLocalStorage;
app.config.globalProperties.$removeLocalStorage = removeLocalStorage;

app.use(router);
app.mount("#app");
